package com.cats.bi.sqltool.function;


import com.cats.bi.sqltool.SQLString;
import com.cats.bi.sqltool.basic.AbstractClause;
import com.cats.bi.sqltool.basic.AbstractColumn;

import java.util.LinkedList;

/**
 * @author wang jian
 * @Description
 * @create 2021/4/7
 */
public class ExprCase extends AbstractColumn<ExprCase> {
    private Object other;
    private LinkedList<Object> kv = new LinkedList<>();

    public ExprCase(String nameAlias) {
        as(nameAlias);
    }

    public ExprCase when(AbstractClause when, Object then) {
        kv.addLast(when);
        kv.addLast(then);
        return this;
    }

    public ExprCase elseAs(Object other) {
        this.other = other;
        return this;
    }

    @Override
    public void toSql(StringBuilder sb) {
        sb.append("CASE ");
        for (Object object : kv) {
            sb.append(" WHEN ");
            SQLString.appendValue(sb, object);
        }
        if (other != null) {
            sb.append(" ELSE ");
            SQLString.appendValue(sb, other);
        }
        sb.append(" END");
    }

}
